package com.tarena.lbs.user.service.impl;

import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.dao.repository.UserRepository;
import com.tarena.lbs.user.dao.repository.UserTagsRepository;
import com.tarena.lbs.user.pojo.param.UserParam;
import com.tarena.lbs.user.pojo.param.UserTagsParam;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.pojo.po.UserTagsPO;
import com.tarena.lbs.user.pojo.vo.UserTagsVO;
import com.tarena.lbs.user.pojo.vo.UserVO;
import com.tarena.lbs.user.service.UserService;
import com.tarena.lbs.user.utils.RandomUserName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserTagsRepository userTagsRepository;

    @Override
    public void register(UserParam param) throws BusinessException {
        String phone = param.getPhone();
        Long count = userRepository.countUserByPhone(phone);
        Asserts.isTrue(count > 0, new BusinessException("-2", "手机号已经存在"));
        //2.封装数据
        UserPO poParam = assembleUserPO(param);
        //3.直接写入数据库
        userRepository.save(poParam);
    }

    @Override
    public UserVO detail() throws BusinessException {
        //1.解析jwt 拿到userPrinciple
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null, new BusinessException("-2", "用户认证解析失败"));
        Integer userId = userPrinciple.getId();
        //2.仓储层查询唯一的po
        UserPO po = userRepository.getById(userId);
        Asserts.isTrue(po == null, new BusinessException("-2", "用户信息不存在"));
        //3.转化vo
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(po, vo);
        return vo;
    }

    @Override
    public void bindUserTags(UserTagsParam param) {
        String tagIds = param.getTagIds();
        java.util.List<String> list = java.util.Arrays.stream(tagIds.split(","))
                .filter(s -> !s.isEmpty()) // 过滤空字符串
                .collect(java.util.stream.Collectors.toList());
        userTagsRepository.deleteByUserId(param.getUserId());
        ArrayList<UserTagsPO> userTagsPOS = new ArrayList<>();
        for (String tagId : list) {
            UserTagsPO userTagsPO = new UserTagsPO();
            userTagsPO.setUserId(param.getUserId());
            userTagsPO.setTagId(Integer.parseInt(tagId));
            userTagsPOS.add(userTagsPO);
        }
        List<UserTagsPO> bindUserTagsPo=userTagsRepository.getUserTags(param.getUserId());
        bindUserTagsPo.stream().map(UserTagsPO::getTagId).collect(Collectors.toList());
        List<UserTagsPO> res = userTagsPOS.stream()
                .filter(newPo -> !bindUserTagsPo.contains(newPo.getTagId()))
                .collect(Collectors.toList());
        userTagsRepository.unBindTags(res);
    }

    @Override
    public List<UserTagsVO> getUserTags(Integer id) {
        ArrayList<UserTagsVO> userTagsVOS = new ArrayList<>();
        List<UserTagsPO> userTagsPOS = userTagsRepository.getUserTags(id);
        for (UserTagsPO userTagsPO : userTagsPOS) {
            UserTagsVO userTagsVO = new UserTagsVO();
            BeanUtils.copyProperties(userTagsPO, userTagsVO);
            userTagsVOS.add(userTagsVO);
        }
        return userTagsVOS;
    }

    @Override
    public void updateUserInfo(UserParam param) {
        // 更新用户信息
        UserPO poToUpdate = new UserPO();
        BeanUtils.copyProperties(param, poToUpdate);
        poToUpdate.setId(param.getId()); // 设置用户ID以确保更新的是正确的记录

        // 调用userRepository.update执行更新操作
        userRepository.update(poToUpdate);
    }


    private UserPO assembleUserPO(UserParam param) {
        UserPO po = new UserPO();
        BeanUtils.copyProperties(param, po);
        //补充必要数据 用户状态 0表示没有绑定标签 1 表示绑定了标签
        po.setStatus(0);
        //用户昵称 注册时候 不是用户填写的 为了快速注册 我们随机生成一个
        String randomName = RandomUserName.createRandomName();//老 大 小  张王李赵
        po.setNickName(randomName);
        po.setUserName(randomName);
        //注册时间
        po.setRegTime(new Date());
        return po;
    }


    @Override
    public Map<String, Integer> getRegisterCount() {
        Map<String, Integer> map = new HashMap<>();
        List<Map<String, Object>> list = userRepository.getRegisterCount();
        for (Map<String, Object> item : list) {
            map.put(item.get("regDate").toString(), Integer.parseInt(item.get("userCount").toString()));
        }
        return map;
    }
}
